<?php
/**
 * User: xialei
 * Date: 2016/6/28 0028
 * Time: 12:24
 */

namespace app\controllers;


use app\commands\CommonTool;
use app\models\User;
use yii\base\Exception;
use yii\base\UserException;
use yii\web\Controller;

class OauthController extends Controller
{
    public function actionLogin()
    {
        $callback = \Yii::$app->urlManager->createAbsoluteUrl(['oauth/callback']);
        return $this->redirect(\Yii::$app->wechat->buildOauthUrl($callback));
    }

    public function actionCallback($code)
    {
        try {
            $accessToken = \Yii::$app->wechat->getOauth2AccessToken($code);
            /** @var User $user */
            $user = User::findOne($accessToken['openid']);
            if (empty($user)) {
                $user = new User();
                $info = \Yii::$app->wechat->getOauth2UserInfo($accessToken['access_token'], $accessToken['openid']);
                $user->setAttributes([
                    'openid' => $info['openid'],
                    'nickname' => $info['nickname'],
                    'avatar' => $info['headimgurl']
                ]);
                if (!$user->save()) {
                    throw new UserException(CommonTool::getFirstError($user));
                }
            }

            \Yii::$app->user->login($user, 7 * 24 * 3600);
            return $this->redirect(['/']);
        } catch (Exception $e) {
            return $this->render('/site/error', [
                'name' => $e->getName(),
                'message' => $e->getMessage()
            ]);
        }
    }

    public function actionAlogin($openid)
    {
        /** @var User $user */
        $user = User::findOne($openid);
        if (!empty($user)) {
            \Yii::$app->user->login($user, 7 * 24 * 3600);
        }
        return $this->redirect(['/']);
    }
}